package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.qo.EmployeeQueryObject;
import cn.wolfcode.qo.PageResult;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.util.UserContext;
import com.alibaba.druid.sql.visitor.functions.If;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.List;

@Service
public class EmployeeServiceImpl implements IEmployeeService{
    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public void delete(Long id) {
        employeeMapper.deleteRelation(id);
        employeeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void save(Employee employee, Long[] ids) {
        //对密码进行加密(把用户名作为盐)
        Md5Hash md5Hash = new Md5Hash(employee.getPassword(), employee.getName());
        employee.setPassword(md5Hash.toString());

        employeeMapper.insert(employee);
        if (ids!=null&&ids.length>0){
            //处理中间表
            for (Long roleId : ids) {
                employeeMapper.insertRelation(employee.getId(),roleId);
            }
        }
    }

    @Override
    public Employee select(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Employee> listAll() {
        return employeeMapper.selectAll();
    }

    @Override
    public void update(Employee employee, Long[] ids) {
        employeeMapper.updateByPrimaryKey(employee);
        //删除原本的关系
        employeeMapper.deleteRelation(employee.getId());
        if (ids!=null&&ids.length>0){
            //处理中间表
            for (Long roleId : ids) {
                employeeMapper.insertRelation(employee.getId(),roleId);
            }
        }
    }

    @Override
    public PageInfo<Employee> query(EmployeeQueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<Employee> employees = employeeMapper.selectForList(qo);
        return new PageInfo<>(employees);
    }

    @Override
    public Employee login(String username, String password) {
        if (!StringUtils.hasLength(username)){
            throw new RuntimeException("用户名不能为空");
        }
        if (!StringUtils.hasLength(password)){
            throw new RuntimeException("密码不能为空");
        }
        Employee employee = employeeMapper.selectByUsernameAndPassword(username,password);
        if (employee==null){
            throw new RuntimeException("用户名或密码不匹配");
        }
        return employee;
    }

    @Override
    public void updateById(String oldPassword,String newPassword, Long id) {
        Employee employee = UserContext.getCurrentUser();
        //判空
        if (!StringUtils.hasLength(oldPassword)){
            throw new RuntimeException("老密码不能为空");
        }
        //判空
        if (!StringUtils.hasLength(newPassword)){
            throw new RuntimeException("新密码不能为空");
        }
        if (oldPassword.equals(employee.getPassword())){
            employeeMapper.updatePasswordById(newPassword,id);
        }else {
            throw new RuntimeException("原密码错误,请重新输入");
        }
    }

    @Override
    public void batchDelete(Long[] ids) {
        employeeMapper.deleteByIds(ids);
    }

    @Override
    public Employee selectByName(String name) {
        return employeeMapper.selectByName(name);
    }

    @Override
    public HSSFWorkbook exportXls() {
        //查询所有的员工
        List<Employee> employees = employeeMapper.selectAll();
        //创建一个excel
        HSSFWorkbook workbook = new HSSFWorkbook();
        //创建sheet
        HSSFSheet sheet = workbook.createSheet("通讯录");
        //创建标题行
        HSSFRow row = sheet.createRow(0);
        //设置标题
        row.createCell(0).setCellValue("姓名");
        row.createCell(1).setCellValue("邮箱");
        row.createCell(2).setCellValue("年龄");
        for (int i = 0; i <employees.size() ; i++) {
            //获取员工
            Employee employee = employees.get(i);
            //创建行
            row = sheet.createRow(i+1);
            //创建单元格
            row.createCell(0).setCellValue(employee.getName());
            row.createCell(1).setCellValue(employee.getEmail());
            if (employee.getAge()!=null){
                row.createCell(2).setCellValue(employee.getAge());
            }
        }
        return workbook;
    }

    @Override
    public void importXls(HSSFWorkbook workbook) {
        //获取第一页的数据
        HSSFSheet sheet = workbook.getSheetAt(0);
        //获取最后一行的行数的索引
        int lastRowNum = sheet.getLastRowNum();
        //标题不需要读 所以从1开始
        for (int i = 1; i <= lastRowNum ; i++) {
            HSSFRow row = sheet.getRow(i);
            Employee employee = new Employee();
            employee.setName(row.getCell(0).getStringCellValue());
            employee.setEmail(row.getCell(1).getStringCellValue());
            HSSFCell cell = row.getCell(2);
            //根据不同的类型来调用不同的方法获取
            if (cell.getCellType().equals(CellType.STRING)){
                //年龄 按照文本格式获取
                String value = row.getCell(2).getStringCellValue();
                employee.setAge(Integer.valueOf(value));
            }else {
                //年龄 按照数字格式获取
                double value = row.getCell(2).getNumericCellValue();
                employee.setAge((int)value);
                //默认密码
                employee.setPassword("1");
                //保存到数据库
                save(employee,null);
            }
        }
    }

    @Override
    public List<Employee> selectByRoleSn(String... sns) {
        List<Employee> sellers = employeeMapper.selectByRoleSn(sns);
        return sellers;
    }
}
